<?php
class Admin_Model_Category {
	
	protected $_db = NULL;
	protected $_tableName = "categories";
	
	/**
	 * construct
	 */
	public function __construct()
	{		
		$this->_db = Zend_Db_Table::getDefaultAdapter();		
	}
		
	/**
	 * @param array $data
	 * @param int $uid
	 * @return int|number
	 */
	public function insert($data, $uid=0)
	{
		$data['created_time'] = date('Y-m-d H:i:s');
		$data['updated_time'] = date('Y-m-d H:i:s');
		$data['created_by'] = $uid;
		$data['updated_by'] = $uid;
		try {
			unset($data['id']);
			$result = $this->_db->insert($this->_tableName, $data);
			return $result;
		} catch (Exception $e) {
			return 0;
		}
	}
	
	/**
	 * update
	 * 
	 * @param array $data
	 * @param int $uid
	 * @return int|number
	 */
	public function update($data, $uid=0)
	{		
		$data['updated_time'] = date('Y-m-d H:i:s');	
		$data['updated_by'] = $uid;
		try {
			$id = $data['id'];
			unset($data['id']);
			$result = $this->_db->update($this->_tableName, $data, "id={$id}");
			return $result;
		} catch (Zend_Db_Adapter_Exception $e) {
			return 0;
		}
	}
	
	/**
	 * @param int $id
	 * @param int $uid
	 * @return int|number
	 */
	public function delete($id, $uid=0)
	{
		try {
			$result = $this->_db->delete($this->_tableName, "id IN ({$id})");
			return $result;
		} catch (Exception $e) {
			return 0;
		}
	}
	
	/**
	 * @return array of category with key as id
	 */
	public function getList($where=array())
	{
		$select = $this->_db->select()
							->from($this->_tableName);
		if (!empty($where))	$select->where(implode(',', $where));							
		$select->order('parent_id ASC');	
		$result = $this->_db->fetchAll($select);
		return $result;
	}
	
	/**
	 * @param int $id
	 * @return array 
	 */
	public function getDetail($id)
	{
		$select = $this->_db->select()
							->from(array('cat' => $this->_tableName))	
							->where('cat.id=?', $id);	
		$result = $this->_db->fetchRow($select);
		return $result;
	}
	
	/**
	 * active
	 * 
	 * @param array $data
	 * @param int $uid
	 * @return int|number
	 */
	public function updateStatus($data, $ids)
	{		
		$data['updated_time'] = date('Y-m-d H:i:s');		
		try {		
			$result = $this->_db->update($this->_tableName, $data, "id IN ({$ids})");
			return $result;
		} catch (Zend_Db_Adapter_Exception $e) {
			return 0;
		}
	}
}